package com.lee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.session.Session;
import org.springframework.session.web.http.HttpSessionStrategy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2017/11/27.
 */
public class MyHttpSessionStrategy implements HttpSessionStrategy {


    //这用Qualifier注解，如果你的工程还集成了spring-data-redis,需要指定一下用哪一个
    @Qualifier("sessionRedisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;
    //过期时间，与session过期时间保持一致
    private Long maxInactiveIntervalInSeconds = 999L;
    private String xxxRedisName = "spring:session:xxx:";
    //当客户端没有传xxx参数的时候，避免创建多个无用的session占用redis空间
    private String defaultSessionId = "default-sessionid";

    /**
     * 客户端传过来的是xxx，需要通过xxx查找映射关系，拿到sessionid返回
     */
    public String getRequestedSessionId(HttpServletRequest request) {
        String xxx = request.getParameter("xxx");
        ValueOperations<String, String> vops = redisTemplate.opsForValue();
        if (xxx != null && !xxx.equals("")) {
            String sessionid = vops.get(xxxRedisName + xxx);
            if(sessionid!=null){
                redisTemplate.expire(xxxRedisName + xxx, maxInactiveIntervalInSeconds, TimeUnit.SECONDS);
            }
            return sessionid;
        } else {
            return vops.get(xxxRedisName+defaultSessionId);
        }
    }

    /**
     * 创建session时，保存xxx和sessionid的映射关系
     */
    public void onNewSession(Session session, HttpServletRequest request,
                             HttpServletResponse response) {
        String xxx = request.getParameter("xxx");
        String sessionid = session.getId();
        ValueOperations<String, String> vops = redisTemplate.opsForValue();
        if (xxx != null && !xxx.equals("")) {
            //保存xxx和sessionid映射关系
            vops.set(xxxRedisName + xxx, sessionid);
            redisTemplate.expire(xxxRedisName + xxx, maxInactiveIntervalInSeconds, TimeUnit.SECONDS);
        }else{
            //没有传xxx时，保存为默认
            vops.set(xxxRedisName+defaultSessionId, sessionid);
            redisTemplate.expire(xxxRedisName+defaultSessionId, maxInactiveIntervalInSeconds, TimeUnit.SECONDS);
        }
    }

    public void onInvalidateSession(HttpServletRequest request,
                                    HttpServletResponse response) {
        String xxx = request.getParameter("xxx");
        redisTemplate.expire(xxxRedisName + xxx, 0, TimeUnit.SECONDS);
    }

}